import React, { PureComponent } from 'react';
import _ from 'lodash';
import { stringify } from 'qs';
import { message } from 'antd';
import { PrimaryGhostC, AdvancedSearch, DATA_ENTRY, codeType, NestedTableC } from '../../../comps';
import moment from 'moment';
import { exportFile } from '@/src/utils/commonFunc';

import { connect } from 'dva';

let SumNum = 0;
@connect(({ BackSellRegisterM, loading }) => ({ BackSellRegisterM, loading }))
export default class BackSellRegister extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      searchObj: {},
      currentPage: 1,
      numInPage: 10,
      total: 0,
      columns: undefined,
      dataSource: undefined,
      isReset: false, // 是否点击重置
      tradingCode: undefined, // 债券的证券代码
      exchangeCode: undefined, // 债券的交易市场代码
      startDate: undefined, // 开始日期
      sessionStartDate: undefined, // 存储session的开始日期（用于重置）
      tenant: undefined, // 租户
      tenantTemp: undefined, // 租户默认值
      jumpTemp: false, // 判断是否从工作台跳过来
      superMan: localStorage.getItem('antd-pro-superMan'), // 当前登录用户是否是超户
    };
  }

  componentDidMount() {
    this.setState({
      superMan: localStorage.getItem('antd-pro-superMan'), // 当前登录用户是否是超户
    });
    SumNum = 0;
    const sessionData = _.cloneDeep(JSON.parse(sessionStorage.getItem('workPlaceResale')));
    this.setState(
      {
        // 若sessionData无数据，默认值startDate - 当天
        startDate: sessionData && JSON.stringify(sessionData) != '{}' ? sessionData.startTime : moment().format('YYYY-MM-DD'), // 开始日期
        sessionStartDate: sessionData && JSON.stringify(sessionData) != '{}' ? sessionData.startTime : moment().format('YYYY-MM-DD'), // 存储session的开始日期
      },
      () => {
        if (this.state.superMan != 'true') {
          this.getTableData();
        }
        sessionStorage.removeItem('workPlaceResale');
      },
    );
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (sessionStorage.getItem('workPlaceResale')) {
      SumNum += 1;
      this.setState({
        jumpTemp: true,
      });
      if (SumNum != 1) {
        const sessionData = _.cloneDeep(JSON.parse(sessionStorage.getItem('workPlaceResale')));
        this.setState(
          {
            // 若sessionData无数据，默认值startDate - 当天
            startDate: sessionData && JSON.stringify(sessionData) != '{}' ? sessionData.startTime : moment().format('YYYY-MM-DD'), // 开始日期
            sessionStartDate: sessionData && JSON.stringify(sessionData) != '{}' ? sessionData.startTime : moment().format('YYYY-MM-DD'), // 存储session的开始日期
          },
          () => {
            this.myData.props.form.resetFields();
            if (this.state.superMan == 'true') {
              this.setState(
                {
                  tenant: this.state.tenantTemp,
                },
                () => {
                  this.getTableData();
                },
              );
            } else {
              this.getTableData();
            }
            sessionStorage.removeItem('workPlaceResale');
          },
        );
      }
    }
  }

  // 销毁前
  componentWillUnmount() {
    sessionStorage.removeItem('workPlaceResale');
  }

  // 获取表格数据
  getTableData = () => {
    const { searchObj, currentPage, numInPage, tenant, superMan, tradingCode, exchangeCode, startDate } = this.state;
    this.props.dispatch({
      type: 'BackSellRegisterM/getTableData',
      payload: {
        requestDate: startDate,
        ...searchObj,
        tenant: superMan ? tenant : undefined,
        tradingCode,
        exchangeCode,
        currentPage,
        numInPage,
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource,
            total: data.pageInfo && data.pageInfo.total,
          });
        }
      },
    });
  };

  // 查询
  queryTableList = (e) => {
    const tempQuery = {};
    for (const k in e) {
      if (k != 'bond' && k !== 'tenant') {
        if (k == 'requestDate') {
          this.setState({
            startDate: e[k].format('YYYY-MM-DD'),
          });
        } else {
          tempQuery[k] = e[k];
        }
      }
    }
    this.setState(
      {
        searchObj: tempQuery,
        isReset: false,
        currentPage: 1,
        numInPage: 10,
        dataSource: [],
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        dataSource: [],
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 导出
  registerExprot = () => {
    const { searchObj, tradingCode, exchangeCode, tenant, superMan, initType, startDate, isReset } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    const tempObj = {
      requestDate: startDate,
      ...searchObj,
      initType,
      tenant: superMan ? tenant : undefined,
      tradingCode,
      exchangeCode,
      currentPage: 1,
      numInPage: 99999,
    };
    const obj = _.cloneDeep(tempObj);
    if (obj) {
      for (const key in obj) {
        if (Array.isArray(obj[key])) {
          obj[key] = obj[key].join(',');
          if (!obj[key]) delete obj[key]; // 如果是空字符 则删除
        }
      }
    }

    exportFile('api/v1/bondsSoldBack/exportExerciseList', obj);
  };

  // 债券下拉事件
  bondOnChange = (e) => {
    if (e) {
      this.setState({
        tradingCode: e.tradingCode,
        exchangeCode: e.exchangeCode,
      });
    } else {
      this.setState({
        tradingCode: undefined,
        exchangeCode: undefined,
      });
    }
  };

  // 租户change事件
  tenantOnChange = (e) => {
    if (e) {
      this.setState(
        {
          tenant: e.info && e.info.value,
        },
        () => {
          if (SumNum == 0 || (this.state.jumpTemp && SumNum == 1)) {
            this.setState({
              tenantTemp: e.info && e.info.value,
            });
            this.getTableData();
            SumNum++;
          }
        },
      );
    } else if (SumNum == 0 || (this.state.jumpTemp && SumNum == 1)) {
      this.setState({
        tenant: undefined,
      });
      message.warning('请选择租户');
    } else {
      this.setState({
        tenant: undefined,
      });
    }
  };

  // 嵌套子表格展开事件
  onchildrenExtend = (expanded, record) => {
    const dataSource = JSON.parse(JSON.stringify(this.state.dataSource));
    const index = dataSource.findIndex((item) => item.id === record.id);
    if (JSON.stringify(record.fundList) != '{}' && expanded) {
      dataSource[index].loading = true;
      const columnsChildren = record.fundList.columns;
      const dataSourceChildren = record.fundList.dataSource;
      columnsChildren &&
        columnsChildren.map((item) => {
          item.width = '300px';
          if (item.key == 'fundName') {
            item.title = '持仓面额（万元）';
          }
        });
      const nestedConfig = {
        columns: columnsChildren,
        dataSource: dataSourceChildren,
        rowKey: 'id',
      };
      dataSource[index].loading = false;
      dataSource[index].nestedConfig = nestedConfig;
      this.setState({
        dataSource,
      });
    }
  };

  render() {
    const { columns, dataSource, total, tenant, superMan, currentPage, numInPage, startDate } = this.state;
    const searchProps = {
      dataSource:
        superMan == 'true'
          ? [
              {
                dataIndex: 'requestDate',
                title: '申请日',
                type: DATA_ENTRY.SINGLEDATE,
                initialValue: moment(startDate),
              },
              {
                dataIndex: 'tenant',
                title: '租户',
                type: DATA_ENTRY.TENANT,
                firstInit: true,
                initialValue: tenant,
                onChange: (e) => {
                  this.tenantOnChange(e);
                },
              },
              {
                dataIndex: 'bond',
                title: '债券',
                type: DATA_ENTRY.SECURITIESCODE,
                codeType: codeType.zq,
                allowClear: true,
                onChange: (e) => this.bondOnChange(e),
              },
            ]
          : [
              {
                dataIndex: 'requestDate',
                title: '申请日',
                type: DATA_ENTRY.SINGLEDATE,
                initialValue: moment(startDate),
              },
              {
                dataIndex: 'bond',
                title: '债券',
                type: DATA_ENTRY.SECURITIESCODE,
                codeType: codeType.zq,
                allowClear: true,
                onChange: (e) => this.bondOnChange(e),
              },
            ],
      // 点击查询按钮
      onQuery: (e) => {
        if (this.state.superMan == 'true') {
          if (this.state.tenant) {
            this.queryTableList(e);
          } else {
            message.warning('请选择租户');
          }
        } else {
          this.queryTableList(e);
        }
      },
      onClear: () => {
        // 点击重置按钮
        this.setState(
          {
            searchObj: {},
            isReset: true,
            tradingCode: undefined,
            exchangeCode: undefined,
            startDate: this.state.sessionStartDate, // 开始日期
            tenant: this.state.superMan == 'true' ? this.state.tenantTemp : undefined,
          },
          () => {
            this.myData.props.form.resetFields();
          },
        );
      },
    };
    return (
      <div>
        <div style={{ marginBottom: '10px' }}>
          <AdvancedSearch
            {...searchProps}
            onRef={(ref) => {
              this.myData = ref;
            }}
          />
        </div>
        <div style={{ margin: '0 10px 10px 10px' }}>
          <PrimaryGhostC onClick={this.registerExprot} title={'导出'} style={{ float: 'right' }} />
          <div style={{ clear: 'both' }}></div>
        </div>
        <NestedTableC
          columns={columns}
          loading={this.props.loading.effects['BackSellRegisterM/getTableData'] == true}
          dataSource={dataSource}
          current={currentPage}
          total={total}
          pageSize={numInPage}
          rowKey='id'
          fixedChild={true}
          onExpand={this.onchildrenExtend}
          onChange={this.handleTableChange}
        />
      </div>
    );
  }
}
